package com.heima.kafka;

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

public class KafkaStreamQuickStart {
    public static void main(String[] args) throws InterruptedException {
        //2. 根据idea的提示创建配置对象并完成配置
        Properties props = new Properties();
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "KafkaStreamQuickStart");

        //3. 根据idea的提示创建streambuilder对象 并编写流失处理的方法
        StreamsBuilder streamsBuilder = new StreamsBuilder();
        processStream(streamsBuilder);

        //1. 创建kafkastream的核心对象
        KafkaStreams kafkaStreams = new KafkaStreams(streamsBuilder.build(), props);

        //4. 开启流式处理
        kafkaStreams.start();

        TimeUnit.SECONDS.sleep(1000);
    }

    private static void processStream(StreamsBuilder streamsBuilder) {
        //1. 订阅一个主题 拉取消息
        KStream<String, String> stream = streamsBuilder.stream("itcast-topic-input");

        //2. 对消息进行转换处理
        stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
            @Override
            public Iterable<String> apply(String value) { //hello world
                System.out.println("收到的消息: value= " + value);
                return Arrays.asList(value.split(" ")); // list[hello,world]
            }
        }).groupBy((key, value) -> value) //3. 分组
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10))) //4. 设置统计的时间窗口
                .count() //5. 统计
                .toStream() //6. 把结果转换未kstream类型
                .map((key, value) -> {
                    System.out.println("key = " + key + "value = " + value);
                    return new KeyValue<>(key.key().toString(), value.toString());
                })
                .to("itcast-topic-output"); //7. 把结果发送到新的topic中暂存起来
    }
}
